﻿ /*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region Using

using System.Data;
using NetBay.Core.BusinessEntities;
using NetBay.Core.DataAccess;
using NetBay.Core.Encryption;
using Rio.Doc.Business.Repository.Translator;
using System.Collections.Generic;
using System;
using NetBay.Core.Log;
using Rio.Doc.DataAccess;
#endregion

namespace Rio.Doc.Business.Repository
{
    /// <summary>
    /// User Repository
    /// </summary>
    public class UserRepository : UserDer
    {



        /// <summary>
        /// Returns the number of user declared
        /// </summary>
        /// <returns>then number of rows in the table</returns>
        public static ReturnLong GetNbUserDeclared()
        {
            var l_oReturnLong = new ReturnLong();
            IDataReader l_oIDataReader = DA_User.GetNbUserDeclared();
            using (l_oIDataReader)
            {
                while (l_oIDataReader.Read())
                {
                    l_oReturnLong.Value = long.Parse(l_oIDataReader["NbUser"].ToString());
                }
            }
            return l_oReturnLong;
        }


        /// <summary>
        /// Returns a user by his login and password
        /// </summary>
        /// <returns>If exists, the user</returns>
        public static User Find(string Login, string Password, Enum.AuthenticationMethod AuthenticationType)
        {

            var l_oUser = new UserRepository();
            switch (AuthenticationType)
            {
                case Enum.AuthenticationMethod.UserPassword:
                    l_oUser = UserTranslator.TranslateFind(DA_User.Find(Login, MD5EncryptorDecryptor.EncodeBase(Password)));
                    break;
                case Enum.AuthenticationMethod.SSO:
                    l_oUser = UserTranslator.TranslateFind(DA_User.Find(Login));
                    break;
            }

            // If the user is valid
            if (l_oUser.IsValid)
            {
                //Geting the group
                l_oUser.SetGroupList();

                //Foreach group
                foreach (GroupDer group in l_oUser.GroupList)
                {
                    group.SetOrganizationList(l_oUser.UserId);
                    group.SetItemRightsList(l_oUser.UserId);
                    group.SetFolderTypeRightList(l_oUser.UserId);
                    //Foreach Organization of each group
                    foreach (OrganizationDer organization in group.OrganizationList)
                    {
                        //Getting the Document type
                        organization.SetFolderTypeList(l_oUser.UserId);
                    }
                }
            }
            return l_oUser;
        }


        /// <summary>
        /// Returns a user by his login and password
        /// </summary>
        /// <returns>If exists, the user</returns>
        public static User Find(string p_sLogin, string p_sPassword, int p_iAuthenticationType)
        {

            var l_oUser = new UserRepository();
            switch (p_iAuthenticationType)
            {
                case (int)Enum.AuthenticationMethod.Ldap:
                    //TODO
                    break;
                case (int)Enum.AuthenticationMethod.UserPassword:
                    l_oUser = UserTranslator.TranslateFind(DA_User.Find(p_sLogin, MD5EncryptorDecryptor.EncodeBase(p_sPassword)));
                    break;
                case (int)Enum.AuthenticationMethod.SSO:
                    l_oUser = UserTranslator.TranslateFind(DA_User.Find(p_sLogin));
                    break;
            }

            // If the user is valid
            if (l_oUser.IsValid)
            {
                //Geting the group
                l_oUser.SetGroupList();

                //Foreach group
                foreach (GroupDer group in l_oUser.GroupList)
                {
                    group.SetOrganizationList(l_oUser.UserId);
                    group.SetItemRightsList(l_oUser.UserId);
                    group.SetFolderTypeRightList(l_oUser.UserId);
                    //Foreach Organization of each group
                    foreach (OrganizationDer organization in group.OrganizationList)
                    {
                        //Getting the Document type
                        organization.SetFolderTypeList(l_oUser.UserId);
                    }
                }
            }
            return l_oUser;
        }

        public static List<User> GetUsersByFolderTypeId(long P_lFolderTypeId)
        {
            var l_oUser = new List<User>();

            // Finaly translate results into a list of users
            l_oUser = UserTranslator.TranslateUsers(DA_User.GetUsersByFolderTypeId(P_lFolderTypeId));

            foreach (var L_oUserOne in l_oUser)
            {
                L_oUserOne.GroupList = GroupTranslator.TranslateGroup(DA_Group.GetGroupByUser(L_oUserOne.UserId));
                foreach (GroupDer group in L_oUserOne.GroupList)
                {
                    group.SetFolderTypeRightList(L_oUserOne.UserId);
                }
            }

            return l_oUser;
        }

        public static List<User> GetUsersByFolderId(string P_sFolderId)
        {
            var l_oUser = new List<User>();

            // Finaly translate results into a list of users
            l_oUser = UserTranslator.TranslateUsers( DA_User.GetUsersByFolderId(P_sFolderId));

            return l_oUser;
        }

        /// <summary>
        /// Gets the users by group id.
        /// </summary>
        /// <param name="groupId">The group id.</param>
        /// <returns></returns>
        public static List<User> GetUsersByGroupId(long groupId)
        {
            return UserTranslator.TranslateUsers(DA_User.GetUsersByGroupId(groupId));
        }

        public static User GetUserById(long P_sUserId)
        {
            var l_oUser = new User();

            // Finaly translate results into a list of users
            l_oUser = UserTranslator.TranslateUser(DA_User.GetUserById(P_sUserId));

            return l_oUser;
        }

        public static void AddAuthorisationsDoc(string P_sFolderId, long P_lUserId)
        {
            DA_User.AddAuthorisationsDoc(P_sFolderId, P_lUserId);
        }

        public static void DeleteAuthorisationsDoc(string P_sFolderId, long P_lUserId)
        {
            DA_User.DeleteAuthorisationsDoc(P_sFolderId, P_lUserId);
        }

        public static List<User> FindAllUser()
        {
            return UserTranslator.TranslateUsers(DA_User.GetAll());
        }

        public static List<string> GetAllEmailUserByGroup(string p_szGroupName)
        {
            return UserTranslator.TranslateEmailUsers(DA_User.GetAllEmailUserByGroupName(p_szGroupName));
        }

        /// <summary>
        /// Add a user's action
        /// </summary>
        /// <param name="p_lUserId">The user identifier</param>
        /// <param name="p_sAction">the user's action</param>
        /// <param name="p_lFolderTypeId">the folder type identifier</param>
        /// <param name="p_sFolderId">the flder Identifier</param>
        /// <param name="p_sDocumentId">the document Identifier</param>
        /// <param name="p_sFileName">The original filename</param>
        public static bool AddUserAction(
            long p_lUserId,
            string p_sAction,
            long p_lFolderTypeId,
            long p_lFolderId,
            string p_sDocumentId,
            string p_sFileName,
            string p_sIndexes,
            string p_sFolderIdDoc = "",
            int p_iCpt = 0,
            bool p_bSauve = false,
            int p_iCptResult = 0,
            int p_iCptIndexed = 0,
            string p_sIndexName = "")
        {
            var l_bReturn = true;

            try
            {
                DA_User.AddUserAction(p_lUserId, p_sAction, p_lFolderTypeId, p_lFolderId, p_sDocumentId, p_sFileName, p_sFolderIdDoc, p_sIndexes, p_iCpt, p_bSauve, p_iCptResult, p_iCptIndexed, p_sIndexName);
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(ex.Message);
                l_bReturn = false;
            }

            return l_bReturn;
        }

        /// <summary>
        /// Updates the user password.
        /// </summary>
        /// <param name="p_lUserId">The P_L user id.</param>
        /// <param name="p_sOldPassword">The P_S old password.</param>
        /// <param name="p_sNewPassword">The P_S new password.</param>
        /// <returns></returns>
        public static bool UpdateUserPassword(long p_lUserId, string p_sOldPassword, string p_sNewPassword)
        {
            return UserTranslator.UpdateUserPassword(DA_User.UpdateUserPassword(p_lUserId, p_sOldPassword, p_sNewPassword));
        }

        /// <summary>
        /// Returns all Group of a user
        /// </summary>
        /// <returns>The list of all Group attached to this user</returns>
        public override void SetGroupList()
        {
            GroupList = GroupTranslator.TranslateGroup(DA_Group.GetGroupByUser(UserId));
        }

        /// <summary>
        /// Adds the user.
        /// </summary>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <param name="email">The email.</param>
        /// <param name="firstName">The first name.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static bool AddUser(string login, string password, string email, string firstName, string name)
        {
            if (password == null)
                password = string.Empty;
            string newPassword = MD5EncryptorDecryptor.EncodeBase(password);
            return DA_User.AddUser(login.ToUpper(), newPassword, email, firstName, name);
        }

        /// <summary>
        /// Adds the user.
        /// </summary>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <param name="email">The email.</param>
        /// <param name="firstName">The first name.</param>
        /// <param name="name">The name.</param>
        /// <param name="groupIds">The group ids.</param>
        /// <returns></returns>
        public static StoredProcedureResult AddUser(string login, string password, string email, string firstName, string name, List<long> groupIds = null)
        {
            if (password == null)
                password = string.Empty;
            string newPassword = MD5EncryptorDecryptor.EncodeBase(password);
            return DA_User.AddUser(login.ToUpper(), newPassword, email, firstName, name, groupIds);
        }

        /// <summary>
        /// Updates the user.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <param name="email">The email.</param>
        /// <param name="firstName">The first name.</param>
        /// <param name="name">The name.</param>
        /// <param name="groupIds">The group ids.</param>
        /// <returns></returns>
        public static StoredProcedureResult UpdateUser(long userId, string login, string password, string email, string firstName, string name, List<long> groupIds = null)
        {
            if (password == null)
                password = string.Empty;

            string newPassword = MD5EncryptorDecryptor.EncodeBase(password);
            return DA_User.UpdateUser(userId, login.ToUpper(), newPassword, email, firstName, name, groupIds);
        }

        /// <summary>
        /// Deletes the user.
        /// </summary>
        /// <param name="userIds">The user ids.</param>
        /// <returns></returns>
        public static StoredProcedureResultCollection DeleteUser(List<long> userIds)
        {
            StoredProcedureResultCollection result = new StoredProcedureResultCollection();
            foreach (long identifier in userIds)
            {
                result.Add(DA_User.DeleteUser(identifier));
            }
            return result;
        }
    }
}
